package com.adgroup.smartnote;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import JsonModel.FamiliarFriend;
import JsonModel.Group;
import JsonModel.Spending;
import JsonModel.User;
import Net.JsonParse;
import Utilities.Configuration;
import ViewFragment.DetailGroupFragment;
import adapter.AdapterCreateNoteExpense;
import adapter.AdapterSearchFriend;
import adapter.AdapterSearchFriend.Adapter;
import adapter.AdapterUserInGroup;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import animationmenu.CollapseAnimationDown;
import animationmenu.ExpandAnimation;
import animationmenu.ExpandAnimationDown;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;

import database.Database;

public class CreateNoteExpenseActivity extends SherlockActivity{

	ListView lv, lvUser;
	ImageButton btnAdd, btnBack, btnSend;
	TextView tvAmount, tvPrice, tvUserChose;
	CheckBox chkAll;
	AdapterCreateNoteExpense.Adapter adapExpense;
	ArrayList<Spending> expenses;
	private View header, footer;
	private ActionBar mActionBar;
	private DisplayMetrics metrics;
	private LinearLayout menuPanel;
	private LinearLayout slidingPanel;
	private boolean isExpanded;
	private int panelWidth;
	private int page = 1;
	private ArrayList<FamiliarFriend> arrs;
	private adapter.AdapterUserInGroup.Adapter adapFriends;
	ProgressBar waiting;
	private View v;
	Group g;
	User u;
	
	@SuppressLint("NewApi")
	@SuppressWarnings("static-access")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.createnote_homekeeper);
		
		//action bar
		mActionBar = getSupportActionBar();
		mActionBar.setDisplayHomeAsUpEnabled(false);
		mActionBar.setDisplayUseLogoEnabled(true);
		mActionBar.setHomeButtonEnabled(true);
		mActionBar.setTitle(getResources().getString(R.string.buttonlogin));
		
		//config menu slide
		metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		
		panelWidth = (int) ((metrics.widthPixels) * 0.85);

		
		menuPanel = (LinearLayout) findViewById(R.id.menuCreateNoteHomeKeeper);
		slidingPanel = (LinearLayout) findViewById(R.id.slideCreateNoteHomeKeeper);
		
		lv = (ListView) findViewById(R.id.listViewCreateNoteHomeKepper);
		lvUser = (ListView) findViewById(R.id.listViewUserFragmentCreateNoteHomeKeeper);
		btnAdd = (ImageButton) findViewById(R.id.imageButtonAddItemCreateNoteHomeKeeper);
		btnSend = (ImageButton) findViewById(R.id.imageButtonSendFragmentCreateNoteHomeKeeper);
		btnBack = (ImageButton) findViewById(R.id.imageButtonBackFragmentCreateNoteHomeKeeper);		
		lvUser = (ListView) findViewById(R.id.listViewUserFragmentCreateNoteHomeKeeper);
		tvAmount = (TextView) findViewById(R.id.textViewTotalAmountFragmentCreateNoteHomeKeeper);
		tvPrice = (TextView) findViewById(R.id.textViewTotalPriceFragmentCreateNoteHomeKeeper);
		tvUserChose = (TextView) findViewById(R.id.textViewUserFragmentCreateNoteHomeKeeper);
		waiting = (ProgressBar) findViewById(R.id.progressBarWaitingUserFragmentCreateNoteHomeKeeper);
		chkAll = (CheckBox) findViewById(R.id.checkBoxAllFragmentCreateNoteHomeKeeper);
		
		//add footer and header
		//add footer iv
		header = CreateNoteExpenseActivity.this.getLayoutInflater().from(CreateNoteExpenseActivity.this).inflate(R.layout.header_createnote_expense, null);
		lv.addHeaderView(header);
		footer = CreateNoteExpenseActivity.this.getLayoutInflater().from(CreateNoteExpenseActivity.this).inflate(R.layout.footer_createnote_expense, null);
		lv.addFooterView(footer);
		v = CreateNoteExpenseActivity.this.getLayoutInflater().from(CreateNoteExpenseActivity.this).inflate(R.layout.footerwating, null);
		lvUser.addFooterView(v);
		v.setVisibility(View.INVISIBLE);
		
		android.widget.FrameLayout.LayoutParams menuPanelParameters = (FrameLayout.LayoutParams) menuPanel
				.getLayoutParams();
		
		menuPanelParameters.setMargins(0, Configuration.screenHeight, 0, 0);
		menuPanel.setLayoutParams(menuPanelParameters);
		//menuPanel.setY(1f);
		menuPanel.setEnabled(false);
		
		//set adapter
		expenses = new ArrayList<Spending>();
		adapExpense = new AdapterCreateNoteExpense(CreateNoteExpenseActivity.this, expenses).new Adapter();
		lv.setAdapter(adapExpense);
		adapExpense.addItem();
		//adapter user chose
		arrs = new ArrayList<FamiliarFriend>();
		adapFriends = new AdapterUserInGroup(CreateNoteExpenseActivity.this, arrs).new Adapter();
		lvUser.setAdapter(adapFriends);
		
		//get user group
		Database db = new Database(CreateNoteExpenseActivity.this);
		u = db.getUser();
		g = db.getGroup();
		arrs = new ArrayList<FamiliarFriend>();
		
		lvUser.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				chkAll.setChecked(false);
				adapFriends.setCheck(arg2);	
			}
		});
		
		btnAdd.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if(adapExpense.checkValidItem()){
					isExpanded = true;
					slidingPanel.setEnabled(false);	
					menuPanel.setEnabled(true);
					arrs.clear();
					page = 1;
					chkAll.setChecked(true);				
					new AsynFriendInGroup().execute();
					// Expand
					new CollapseAnimationDown(menuPanel, Configuration.screenHeight,
							0, 0.0f,
						0, 0.0f, Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0f);
				}
			}
		});
		btnBack.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {//ExpandAnimationDown
				isExpanded = false;
				slidingPanel.setEnabled(true);	
				menuPanel.setEnabled(false);	
				
				// Expand
				new ExpandAnimationDown(menuPanel, Configuration.screenHeight,
						0, 0.0f,
						0, 0.0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 1f);
			}
		});
		chkAll.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				adapFriends.setAllCheck(chkAll.isChecked());	
				if(chkAll.isChecked()){
					tvUserChose.setVisibility(View.VISIBLE);
				}
				else{
					tvUserChose.setVisibility(View.INVISIBLE);
				}		
			}
		});
		
		btnSend.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				
			}
		});
		footer.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				int add = adapExpense.addItem();
				if(add==1){
					new AlertDialog.Builder(CreateNoteExpenseActivity.this)
					.setTitle(getResources().getString(R.string.titlealerterrorcreategroup))
					.setMessage(getResources().getString(R.string.alert_message_amount_require))
					.setPositiveButton(getResources().getString(R.string.ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
								}
					}).show();
				}
				else if(add==2){
					new AlertDialog.Builder(CreateNoteExpenseActivity.this)
					.setTitle(getResources().getString(R.string.titlealerterrorcreategroup))
					.setMessage(getResources().getString(R.string.alert_message_description_require))
					.setPositiveButton(getResources().getString(R.string.ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
								}
					}).show();
				}
				else if(add==3){
					new AlertDialog.Builder(CreateNoteExpenseActivity.this)
					.setTitle(getResources().getString(R.string.titlealerterrorcreategroup))
					.setMessage(getResources().getString(R.string.alert_message_price_require))
					.setPositiveButton(getResources().getString(R.string.ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
								}
					}).show();
				}
			}
		});
		
	}

	//load search friend by key
	class AsynFriendInGroup extends AsyncTask<Void, Void, String>
	{
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			if(page==1){
				waiting.setVisibility(View.VISIBLE);
			}
			else{
				v.setVisibility(View.VISIBLE);
			}
		}
		@Override
		protected String doInBackground(Void... params) {
			return new JsonParse().getUserInGroup(CreateNoteExpenseActivity.this, g.getGroupId(), u.getUserId(), page++);
		}
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			try {
				JSONObject json = new JSONObject(result);
				String res = json.getString(Configuration.result);
				Log.d("log",res);
				if(!res.equalsIgnoreCase(Configuration.norow)){
					JSONArray arr = json.getJSONArray(Configuration.result);
					for(int i=0;i<arr.length();i++){
						JSONObject obj = arr.getJSONObject(i);
						String userid = obj.getString(FamiliarFriend.keyUserId);
						String email = obj.getString(FamiliarFriend.keyGmail);
						String nickname = obj.getString(FamiliarFriend.keyNickName);
						String time = obj.getString(FamiliarFriend.keyTime);
						String link = obj.getString(FamiliarFriend.keyLink);
						
						FamiliarFriend f = new FamiliarFriend(userid, nickname, time, link, email, true);
						arrs.add(f);
					}
					adapFriends.setFriends(arrs);
					if(page==2){
						adapFriends.setAllCheck(true);	
						tvUserChose.setText(adapFriends.getCount()+ " " +getResources().getString(R.string.user_chose));
						tvUserChose.setVisibility(View.VISIBLE);
					}
					else{
						adapFriends.notifyDataSetChanged();
					}
					Log.d("log",arrs.size()+"");
				}
				else{
					
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			waiting.setVisibility(View.INVISIBLE);
			v.setVisibility(View.INVISIBLE);
			
		}
	}

	public void updateUserChose(int count) {
		chkAll.setChecked(false);
		if(count==0){
			tvUserChose.setVisibility(View.INVISIBLE);
		}
		else{
			tvUserChose.setText(count+ " " +getResources().getString(R.string.user_chose));
			tvUserChose.setVisibility(View.VISIBLE);
		}
	}
}
